import UIKit
import Flutter
import KTVHTTPCache

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
      startKTV()
      bindMethod(messenger: window?.rootViewController as! FlutterBinaryMessenger)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    
    func startKTV() {
        try? KTVHTTPCache.proxyStart()
    }
    
    func bindMethod(messenger: FlutterBinaryMessenger) {
        let channel = FlutterMethodChannel(name: "ktvcache", binaryMessenger: messenger);
        channel.setMethodCallHandler { call, result in
            if call.method == "precache" {
                if let urls = call.arguments as? [String] {
                    for urlStr in urls {
                        if let url = URL(string: urlStr),urlStr.starts(with: "http") {
                            let request = KTVHCDataRequest(url: url, headers: [:])
                            let loader = KTVHTTPCache.cacheLoader(with: request);
                            loader?.prepare()
                        }
                    }
                }
            } else if call.method == "localURL" {
                if let arg = call.arguments as? [String:Any], let url = arg["url"] {
                    let u = KTVHTTPCache.proxyURL(withOriginalURL: URL(string: url as! String))
                    result(u?.absoluteString)
                }
            }
        }
    }
}


class SwiftFlutterPlugin: NSObject, FlutterPlugin {
    static func register(with registrar: any FlutterPluginRegistrar) {
        SwiftFlutterPlugin.register(with: registrar)
    }
    
    
    
}
